<template>
  <div class="app-container">
    <div style="padding: 20px;">
      <el-row>
        <el-col :span="4">
          <strong style="font-size: 20px;">
            新增/修改
          </strong>
        </el-col>
      </el-row>

      <div style="padding:20px">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="用户名">
            <el-input v-model="form.username" :disabled="disabled" />
          </el-form-item>
          <el-form-item label="门店">
            <el-select
              v-model="form.store"
              filterable
              clearable
              @change="$forceUpdate()"
            >
              <el-option
                v-for="item in stores"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="form.plainPassword" />
          </el-form-item>
          <el-form-item label="类型">
            <el-select
              v-model="form.type"
              filterable
              clearable
              @change="$forceUpdate()"
            >
              <el-option
                v-for="item in types"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否激活">
            <el-checkbox v-model="form.enabled" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      id: Number(this.$route.params.id),
      stores: [],
      types: [
        { label: '收银', value: 'cashier' },
        { label: '财务', value: 'finance' },
        { label: '人事', value: 'personnel' },
        { label: '考勤', value: 'attendance' }
      ],
      form: {
        username: '',
        plainPassword: '',
        store: null,
        type: null,
        enabled: true
      },
      disabled: false
    }
  },
  created() {
    this.getStores()
    if (this.id) {
      this.disabled = true
      this.axios.get(`/manage/officers/${this.id}`, { params: {
        '@expands': `['entity.user']`
      }}).then((res) => {
        this.form.userId = res.data.user.id
        this.form.store = res.data.store ? res.data.store.id : null
        this.form.type = res.data.type
        this.form.username = res.data.user.__metadata.username
        this.form.enabled = res.data.enabled
      })
    }
  },
  methods: {
    getStores() {
      this.axios.get(`/manage/stores`, {
        params: {
          limit: 10000000
        }
      }).then(res => {
        this.stores = res.data
      })
    },
    onSubmit() {
      if (!this.form.type) {
        this.$message.error('请选择账号类型！')
        return
      }
      if (!this.form.store) {
        this.$message.error('请选择门店！')
        return
      }
      const roles = ['ROLE_USER']
      if (this.form.type === 'finance') {
        roles.push('ROLE_FINANCE')
      } else if (this.form.type === 'personnel') {
        roles.push('ROLE_PERSONNEL')
      } else if (this.form.type === 'cashier') {
        roles.push('ROLE_CASHIER')
      } else if (this.form.type === 'attendance') {
        roles.push('ROLE_ATTENDANCE')
      }

      if (this.id) {
        const loading = this.$loading({
          lock: true,
          text: '数据交互中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        if (this.form.plainPassword) {
          this.axios.put(`/manage/users/${this.form.userId}/change-password`, { password: this.form.plainPassword })
        }
        this.axios.put(`/manage/users/${this.form.userId}`, {
          roles: roles
        }).then((update) => {
          this.axios.put(`/manage/officers/${this.id}`, {
            store: this.form.store,
            type: this.form.type,
            enabled: this.form.enabled
          }).then((res) => {
            this.$message.success('修改成功！')
            this.$router.go(-1)
            loading.close()
          })
        })
      } else {
        if (!this.form.username) {
          this.$message.error('请填写用户名！')
          return
        }
        if (this.form.username === 'admin' || this.form.username === 'platform') {
          this.$message.error('禁用名！')
          return
        }
        if (!this.form.plainPassword) {
          this.$message.error('请填写密码！')
          return
        }

        const loading = this.$loading({
          lock: true,
          text: '数据交互中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.axios.get(`/manage/users`, { params: {
          '@filter': `entity.getUsername() == "${this.form.username}"`
        }}).then((res) => {
          if (res.data.length > 0) {
            const user = res.data[0]
            if (!user.enabled) {
              loading.close()
              this.$message.error('此用户名账号已停用！')
              return
            }
            if (user.officer) {
              loading.close()
              this.$message.error('此用户名已建立账号信息！')
              return
            }

            this.axios.put(`/manage/users/${user.id}`, {
              roles: roles
            }).then((update) => {
              this.axios.post(`/manage/officers`, {
                user: user.id,
                store: this.form.store,
                type: this.form.type,
                enabled: this.form.enabled
              }).then(officer => {
                loading.close()
                this.$message.success('修改成功！')
                this.$router.go(-1)
              })
            })
          } else {
            this.axios.post(`/manage/users`, {
              username: this.form.username,
              email: this.form.username + '@email.com',
              enabled: true,
              roles: roles,
              plainPassword: this.form.plainPassword
            }).then(user => {
              this.axios.post(`/manage/officers`, {
                user: user.data.id,
                store: this.form.store,
                type: this.form.type,
                enabled: this.form.enabled
              }).then(officer => {
                loading.close()
                this.$message.success('修改成功！')
                this.$router.go(-1)
              })
            })
          }
        })
      }
    }
  }
}
</script>
